package be.kuleuven.mume.hulpklassen;

import java.io.IOException;

import be.kuleuven.mume.R;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

public class AuthenticatedChecker implements AccountManagerCallback<Bundle>{
	private final static String TOKEN_TYPE = "ah";
	private Context context;
	private AuthenticatedListener listener;
	private boolean showDialog = false;
	private boolean isBusy = false;
	
	public abstract interface AuthenticatedListener{
		public abstract void AuthenticationReceived();
	}
	
	public AuthenticatedChecker(Context context, AuthenticatedListener listener) {
		this.context = context;
		this.listener = listener;
	}

	protected void onGetAuthToken(Bundle bundle) {
		if(this.listener != null)
			this.listener.AuthenticationReceived();
	}

	public void checkAuthenticated(boolean showdialog){
		if(this.isBusy)
			return;
		this.isBusy = true;
		this.showDialog = showdialog;
		
		AccountManager accountManager = AccountManager.get(context);
		Account[] accounts = accountManager.getAccountsByType("com.google");

		if (accounts == null || accounts.length == 0) {
			Toast t = Toast.makeText(context, R.string.no_account, 10);
			t.show();
			this.isBusy = false;
			return;
		}

		Account account = accounts[0];
		accountManager.getAuthToken(account, TOKEN_TYPE, true, this, null);
	}

	public void run(AccountManagerFuture<Bundle> result) {
		Bundle bundle;
		try {
			bundle = result.getResult();
			Intent intent = (Intent)bundle.get(AccountManager.KEY_INTENT);
			if(intent != null) {
				if(showDialog)
				// User input required
					context.startActivity(intent);
			} else {
				onGetAuthToken(bundle);
			}
		} catch (OperationCanceledException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (AuthenticatorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.isBusy = false;
	}
}
